/*
 * ConnectEventResource.cpp
 *
 *  Created on: 2013. 12. 26.
 *      Author: mega
 */

#include "../User.h"
#include "../NUtil/Utils.h"
#include "../NLogic/Function.h"
#include "../NLogic/Reward.h"
#include "../NLogic/MailBox.h"

#include "Static.h"
#include "ConnectEventResource.h"

#include <Database/Static.h>

namespace ProjectZ { namespace NResource {

ConnectEventResource::ConnectEventData::ConnectEventData()
{

}

ConnectEventResource::ConnectEventData::~ConnectEventData()
{
	std::for_each(clsFlyVector.begin(), clsFlyVector.end(), [&](ConnectEventData::Flyweight * pFly) {
		delete pFly;
	});
}

ConnectEventResource::ConnectEventResource()
{
	pConnectEventAD		= new ConnectEventData;
	pConnectEventIOS	= new ConnectEventData;
}

ConnectEventResource::~ConnectEventResource()
{
	delete pConnectEventAD;
	delete pConnectEventIOS;
}

void
ConnectEventResource::ConnectEventData::Clear()
{
	std::for_each(clsFlyVector.begin(), clsFlyVector.end(), [&](ConnectEventData::Flyweight * pFly) {
		delete pFly;
	});
	clsFlyVector.clear();
}

bool
ConnectEventResource::LoadResource()
{
	if (false == pConnectEventAD->LoadResource(MARKET_GOOGLE, SC_KAKAO_GOOGLE))
		return false;

	if (false == pConnectEventIOS->LoadResource(MARKET_IOS, SC_KAKAO_IOS))
		return false;

	return true;
}

bool
ConnectEventResource::ConnectEventData::LoadResource(int company, int salecode)
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT NATIONAL_CODE, REWARD_TYPE, ITEM_SHEETTYPE, ITEM_TID, "
			"ITEM_QUANTITY, GOLD, ZEN, UNIX_TIMESTAMP(START_DATE), UNIX_TIMESTAMP(END_DATE), MESSAGE "
			"FROM resource_connect_event_new WHERE COMPANY=%d AND SALE_CODE=%d", company, salecode);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if (clsAuto->GetErrorIdx() != 0)
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while (clsAuto->Next())
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		ConnectEventData::Flyweight * pFly = new ConnectEventData::Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_REWARD_TYPE >> pFly->_ITEM_SHEETTYPE >> pFly->_ITEM_TID
			>> pFly->_ITEM_QUANTITY >> pFly->_GOLD >> pFly->_ZEN >> pFly->_START_DATE >> pFly->_END_DATE >> pFly->_MESSAGE;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyVector.push_back(pFly);
	}

	return true;
}

ConnectEventResource::ConnectEventData::Flyweight *
ConnectEventResource::ConnectEventData::GetEvent()
{
	time_t curTime = time(NULL);

	auto iter = clsFlyVector.begin();

	for (; iter != clsFlyVector.end(); ++iter)
	{
		Flyweight * pFly = (* iter);

		if (pFly->_START_DATE <= curTime && curTime <= pFly->_END_DATE)
		{
			return pFly;
		}
	}

	return NULL;
}

ConnectEventResource::ConnectEventData::Flyweight *
ConnectEventResource::GetEvent(User * pUser)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(pUser->GetCompany(), pUser->GetSaleCode());

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pConnectEventAD->GetEvent();

	case NUtil::MarketType::IOS_KAKAO:
		return pConnectEventIOS->GetEvent();

	default:
		return NULL;
	}
}

bool
ConnectEventResource::SendConnectEventReward(User * pUser)
{
	ConnectEventData::Flyweight * pFly = this->GetEvent(pUser);
	if (NULL == pFly)
		return false;

	// 이미 보상을 받았는지 여부 확인
	if (false == IsRecvReward(pUser, pFly))
		return false;


	// 보상 받은 시간 기록
	int index = static_cast<int>(NLogic::Reward::RewardType::CONNECT_EVENT);
	pUser->GetUserInfo().array_Slot[index].reg_date = time(NULL);
	pUser->FlushUserInfoCache();

	// 보상 없음
	if (0 >= pFly->_REWARD_TYPE)
		return true;

	// 골드와 ZEN은 하나의 메일로 발송한다
	{
		NLogic::MailBox::Mail::Data clsMailData;
		clsMailData.send_user_seq		= 0;
		clsMailData.send_user_nickname	= "GAMEVIL";
		clsMailData.recv_user_seq		= pUser->GetUserSeq();
		clsMailData.message				= pFly->_MESSAGE.c_str();

		bool bSendMail = false;

		if (pFly->_REWARD_TYPE & EM_GIFT_GOLD)
		{
			clsMailData.gift_status	|= EM_GIFT_GOLD;
			clsMailData.gold		= pFly->_GOLD;
			bSendMail				= true;
		}

		if (pFly->_REWARD_TYPE & EM_GIFT_ZEN)
		{
			clsMailData.gift_status		|= EM_GIFT_ZEN;
			clsMailData.gift_vcindex	= EM_VCINDEX_ADMIN_MAIL_EVENT;
			clsMailData.zen				= pFly->_ZEN;
			bSendMail					= true;
		}

		// 메일 발송
		if (true == bSendMail)
		{
			if (false == NLogic::NFunction::SendMail(pUser, clsMailData))
			{
				DEBUGLOG("SendConnectEventReward : GOLD & ZEN Mail Send Fail!!");
				return false;
			}
		}
	}

	// 아이템은 메일을 따로 발송한다
	{
		if (pFly->_REWARD_TYPE & EM_GIFT_ITEM)
		{
			NLogic::MailBox::Mail::Data clsMailData;
			clsMailData.send_user_seq		= 0;
			clsMailData.send_user_nickname	= "GAMEVIL";
			clsMailData.recv_user_seq		= pUser->GetUserSeq();
			clsMailData.message				= pFly->_MESSAGE.c_str();
			clsMailData.gift_status			= EM_GIFT_ITEM;

			NLogic::Item::Data clsItemData;
			clsItemData.tid			= pFly->_ITEM_TID;
			clsItemData.sub_type	= pFly->_ITEM_SHEETTYPE;
			clsItemData.class_type	= -1;

			int isStack = Static::InstancePtr()->GetItemResource()->getItemStackType(clsItemData);

			int sendMailCount	= 0;
			int itemQuantity	= 0;

			// 스택 아이템이 아니면서, 보상 수량이 2개 이상인 경우는 아이템을 하나씩 첨부하여 메일을 각각 발송한다.
			if (1 != isStack && pFly->_ITEM_QUANTITY >= 2)
			{
				itemQuantity	= 1;
				sendMailCount	= pFly->_ITEM_QUANTITY;
			}
			else
			{
				itemQuantity	= pFly->_ITEM_QUANTITY;
				sendMailCount	= 1;
			}

			if (false == Static::InstancePtr()->GetItemResource()->SetItemFromXLS(pUser, clsMailData.item, pFly->_ITEM_SHEETTYPE, pFly->_ITEM_TID, itemQuantity))
			{
				DEBUGLOG("SendConnectEventReward : ITEM Setting Fail!!");
				return false;
			}

			for (int i = 0; i < sendMailCount; i++)
			{
				if (false == NLogic::NFunction::SendMail(pUser, clsMailData))
				{
					DEBUGLOG("SendConnectEventReward : ITEM Mail Send Fail!!");
					return false;
				}
			}
		}
	}

	return true;
}

bool
ConnectEventResource::IsRecvReward(User * pUser, ConnectEventData::Flyweight * pFly)
{
	/*
	 * 이미 보상을 받았는지 확인 한다
	 */
	int index = static_cast<int>(NLogic::Reward::RewardType::CONNECT_EVENT);

	if (0 == pUser->GetUserInfo().array_Slot[index].reg_date)
	{
		return true;
	}

	// 이미 보상을 받은 경우
	if (pFly->_START_DATE <= static_cast<time_t>(pUser->GetUserInfo().array_Slot[index].reg_date)
			&& static_cast<time_t>(pUser->GetUserInfo().array_Slot[index].reg_date) <= pFly->_END_DATE)
	{
		return false;
	}

	return true;
}

} /*NResource*/ } /*ProjectZ*/
